package mysql

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"go-gin-init/app/core"
	"go.uber.org/zap"
	"log"
	"strings"
	"time"
)

var _sqlDb *sqlx.DB

func InitSqlx() {

	mySqlConfig := core.Conf.DataBase
	host := mySqlConfig.Host
	port := mySqlConfig.Port
	database := mySqlConfig.DbName
	username := mySqlConfig.Username
	password := mySqlConfig.Password
	charset := mySqlConfig.Charset

	dsn := strings.Join([]string{username, ":", password, "@tcp(", host, ":", port, ")/", database, "?charset=" + charset + "&parseTime=true"}, "")

	db, err := sqlx.Connect("mysql", dsn)
	if err != nil {
		log.Println(err)
		zap.L().Error("数据库连接失败")
	}

	db.SetConnMaxLifetime(time.Second * 60)
	db.SetMaxIdleConns(5)
	db.SetMaxOpenConns(20)
	db.SetConnMaxIdleTime(time.Second * 60)
	db.SetConnMaxLifetime(time.Second * 10)
	db.SetConnMaxIdleTime(time.Second * 30)

	_sqlDb = db
}

func GetSqlxDB() *sqlx.DB {
	return _sqlDb
}
